﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Reflection;

namespace tester
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void log(string s)
        {
            //edLog.Text += "\n" + s;
            edLog.Items.Add(s);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            log("Beginned to " + tbUrl.Text);
            NavigateToUrl(tbUrl.Text);
            GetRudaFromMetro();

            //browser.Navigate(tbUrl.Text);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //log("Current doc completed!");
            DocComplete = true;
        }

        public void button2_Click(object sender, EventArgs e)
        {
            GoToMetro();
        }

        public void postData2(WebBrowser br, string key, string data)
        {
            //HtmlElement mainForm = null;
            return;
            //if (mainForm == null)
            //{
            //    log("Cannot find main form!");
            //    return;
            //}
            //log("Processing main form.......");
            //string additionalForm = "<form action=\"http://moswar.ru/metro/\" method=\"POST\" style=\"display:none;\" id=\"service-form\">";
            //additionalForm += "<input type=\"hidden\" name=\"" + key + "\" value=\"" + data + "\">";
            //additionalForm += "</form>";
            ////mainForm.

        }

        void postData(WebBrowser br, string data)
        {
            Uri uri = br.Url;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
            req.Method = "POST";
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bPostData = enc.GetBytes(data);
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bPostData.Length;
            Stream stream = req.GetRequestStream();
            stream.Write(bPostData, 0, bPostData.Length);
            log("After writing ContentLength=" + req.ContentLength.ToString());
            stream.Close();
            WebResponse resp = req.GetResponse();
            log("Responsed to " + resp.ResponseUri.ToString());
            br.Navigate(resp.ResponseUri);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            edLog.Items.Clear();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            log("requestSkills() result: " + requestSkills().ToString());
        }

        private Results requestTimeAlley(out int to)
        {
            to = -1;
            NavigateToUrl("moswar.ru/alley");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            HtmlElement searchForm = browser.Document.Forms["searchForm"];
            if (searchForm == null) return Results.InternalError;
            log("Нашли форму для поиска");
            foreach (HtmlElement elem in searchForm.GetElementsByTagName("p")) 
            {
                string elemClassName = elem.GetAttribute("className");
                if (elemClassName == "timer first-child" || elemClassName == "timer") 
                {
                    HtmlElement spanTimer = elem.GetElementsByTagName("span")[0];
                    if (spanTimer == null) return Results.InternalError;
                    to = int.Parse(spanTimer.GetAttribute("timer"));
                    log("Надо ждать " + to.ToString());

                    return Results.Success;
                }
                log("Skipping: " + elem.OuterHtml);

            }
            return Results.NoNeedToWait;
        }

        private Results requestTimeMetro(out int to)
        {
            to = -1;
            NavigateToUrl("moswar.ru/metro");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            HtmlElement elem = browser.Document.GetElementById("metrodig");
            if (elem != null) 
            {
                log("Нашли элемент id=metrodig");
                to = int.Parse(elem.GetAttribute("timer"));
                return Results.Success;
            }
            elem = browser.Document.GetElementById("welcome-rat");
            if (elem != null) 
            {
                if (elem.Style != "DISPLAY: none")
                {
                    log("Нашли крысомаху: style=" + elem.Style);
                    return Results.RatMeeting;
                }
            }
            foreach (HtmlElement elBranch in browser.Document.GetElementsByTagName("div")) 
            {
                if (elBranch.GetAttribute("className") == "metro-branch") 
                {
                    elem = elBranch.GetElementsByTagName("div")[0];
                    if (elem != null && elem.InnerText == "Спуститься в туннель") 
                    {
                        return Results.NeedToHarvest;
                    }
                }
            }
            return Results.NoNeedToWait;
        }

        Results GoToMetro()
        {
            NavigateToUrl("http://moswar.ru/metro/");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            browser.Document.InvokeScript("metroWork");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            usedKirka--;
            return Results.Success;
        }

        private void LeaveMetro()
        {
            browser.Document.InvokeScript("metroLeave2");
        }

        private Results GetRudaFromMetro()
        {
            if (!browser.Url.ToString().EndsWith("/metro/")) return  Results.InternalError;
            // поиск элемента раскопок руды
            bool founded = false;
            foreach (HtmlElement elem in browser.Document.GetElementsByTagName("div")) 
            {
                if (elem.GetAttribute("className") == "metro-branch") 
                {
                    string percent = elem.GetElementsByTagName("p")[1].GetElementsByTagName("b")[0].InnerText.Split('%')[0];
                    int proc = int.Parse(percent);
                    log("Вероятность нахождения руды "+proc.ToString());
                    founded = true;
                    if (proc > nudRudaPercent.Value)
                    {
                        DocComplete = false;
                        browser.Document.InvokeScript("metroDig");
                        while (!DocComplete) Application.DoEvents();
                        usedGager--;
                        UpdateTugriks();
                    }
                    else 
                    {
                        log("Вероятность слишком мала. Поднимаемся наружу");
                        LeaveMetro();

                    }
                    break;
                }
            }
            if (!founded) 
            {
                log("Не смогли найти форму для руды!");
                return Results.InternalError;
            }
            return Results.Success;
        }

        #region Naviration
        private bool DocComplete = false;
        private bool NavigationDelayFinished = false;
        private void NavigationDelayer_Tick(object sender, EventArgs e)
        {
            NavigationDelayFinished = true;
        }
        private bool ClosingWindow = false;
        private bool blockedClose = false;
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = blockedClose;
            ClosingWindow = true;
        }
        public void WaitAfterNavigation() 
        {
            blockedClose = true;
            while (!DocComplete && !ClosingWindow) Application.DoEvents();
            DocComplete = false;
            NavigationDelayer.Start();
            while (!NavigationDelayFinished && !ClosingWindow) Application.DoEvents();
            NavigationDelayer.Stop();
            NavigationDelayFinished = false;
            blockedClose = false;
            if (ClosingWindow) Close();
        }
        private void NavigateToUrl(string url)
        {
            browser.Navigate(url);
            WaitAfterNavigation();
            UpdateTugriks();
        } 
        #endregion

        string Tugriki = "??";
        int Ruda = 0;
        string Med = "??";
        string NamePerson = "??";
        //string NanoPetriks = "???";
        int WantedPercent = -1;

        public void UpdateTugriks()
        {
            Tugriki = "??";
            Ruda = -1;
            Med = "??";
            NamePerson = "??";
            HtmlElement elemPersonal = null;
            try
            {
                elemPersonal = browser.Document.GetElementById("personal");
            }
            catch (Exception)
            {
                return;
            }
            int i = 0;
            if (elemPersonal != null)
            {
                foreach (HtmlElement e in elemPersonal.GetElementsByTagName("li"))
                {
                    i++;
                    string s = e.OuterText.Substring(2);
                    if (s.IndexOf(",") >= 0) s = s.Remove(s.IndexOf(","), 1);
                    switch (i)
                    {
                        case 1:
                            Tugriki = s;
                            //log("Кол-во денег:" + Tugriki);
                            break;
                        case 2:
                            Ruda = int.Parse(s);
                            break;
                        case 3:
                            Med = s;
                            break;

                    }
                }
                foreach (HtmlElement e in elemPersonal.GetElementsByTagName("div"))
                    if (e.GetAttribute("className") == "wanted")
                        foreach (HtmlElement e2 in e.GetElementsByTagName("div"))
                            if (e2.GetAttribute("className") == "percent")
                            {
                                WantedPercent = e2.ClientRectangle.Width;
                                //log("width=" + WantedPercent);
                            }

                foreach (HtmlElement e in elemPersonal.GetElementsByTagName("a"))
                {
                    if (e.GetAttribute("href").EndsWith("/player/"))
                    {
                        NamePerson = e.OuterText;
                        //log("Нашли имя персонажа: " + lbNamePerson.Text + ", тугриков:" + lbTugriki.Text);
                    }
                }
            }
            lbTugriki.Text = Tugriki;
            lbRuda.Text = Ruda.ToString();
            lbMed.Text = Med;
            lbNamePerson.Text = NamePerson;
            lbWanted.Text = ((WantedPercent - 50) / 10).ToString();
            lbWanted.Text = WantedPercent.ToString()+"%";
            return;
        }

        enum EnemyType
        {
            equal = 0,
            strong = 1,
            weak = 2,
            enemy = 3,
            victim = 4,
        }

        Results tryFindEnemies(EnemyType type)
        {
            string enemyTyle = type.ToString();
            NavigateToUrl("moswar.ru/alley/");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            if (browser.Url.LocalPath == "/metro/") return Results.NeedMetroWork;
            HtmlElement elSearchForm = browser.Document.Forms["searchForm"];
            if (elSearchForm == null)
            {
                log("Не найдена форма searchForm");
                return  Results.InternalError;
            }
            log("Свободен для боев!");

            //setting type of enemy
            HtmlElement selector = elSearchForm.GetElementsByTagName("select")["type"].GetElementsByTagName("option")[0];
            selector.SetAttribute("value", enemyTyle);

            // getting opponent
            elSearchForm.InvokeMember("submit");
            WaitAfterNavigation();
            UpdateTugriks();
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            if (browser.Url.LocalPath == "/metro/") return Results.NeedMetroWork;

            elSearchForm = browser.Document.Forms["searchForm"];
            if (elSearchForm != null)
            {
                log("Ошибка поиска соперника");
                return  Results.AlleyNeedToWait;
            }
            log("МАХЫЧ!!!");
            HtmlElement machich = null;
            foreach (HtmlElement e in browser.Document.GetElementsByTagName("div"))
            {
                if (e.GetAttribute("className").StartsWith("button button-fight"))
                {
                    machich = e.GetElementsByTagName("a")[0];
                    if (machich != null)
                    {
                        log("Жмем на атаку ");
                        machich.InvokeMember("click");
                        WaitAfterNavigation();
                        if (browser.Url.LocalPath == "/police/") return Results.InPolice;
                        if (browser.Url.LocalPath == "/metro/") return Results.NeedMetroWork;
                        break;
                    }
                }
            }
            if (machich == null)
            {
                log("Какие-то технические проблемы!");
                return  Results.InternalError;
            }
            if (!browser.Url.ToString().StartsWith("http://www.moswar.ru/alley/fight"))
            {
                log("Почему-то не вошли вошли бой!");
                return  Results.InternalError;
            }
            string TugrikWin = "??";
            string Rating = "??";
            string Opponent = "??";
            bool iwin = AnalyseFight(out TugrikWin, out Rating, out Opponent);
            log("Бой состоялся");
            if (iwin) 
            {
                log("Правда была за нами! Получено " + TugrikWin + " тугриков и "+Rating+" опыта от игрока "+Opponent);
            }
            return Results.Success;
        }

        private bool AnalyseFight(out string TugrikWin, out string Rating, out string Opponent)
        {
            TugrikWin = "??";
            Rating = "??";
            Opponent = null;
            browser.Document.InvokeScript("fightForward");
            string winner = "??";
            // поиск оппонента
            foreach (HtmlElement elem in browser.Document.GetElementsByTagName("div")) 
            {
                if (elem.GetAttribute("className") == "fighter2")
                {
                    Opponent = elem.InnerText.Split('[')[0];
                    break;
                }
            }
            if (Opponent == null) 
            {
                Opponent = "??";
                log("ОШИБКА ПОИСКА ОПОНЕНТА!!!");
            }
            // Поиск результатов
            foreach (HtmlElement elem in browser.Document.GetElementsByTagName("li"))
            {
                if (elem.GetElementsByTagName("A").Count > 0)
                    if (elem.GetElementsByTagName("A")[0].GetAttribute("href") == browser.Url.ToString())
                    {
                        HtmlElementCollection result = elem.GetElementsByTagName("div");
                        if(result ==null || result.Count<2)break;
                        log("Нашли результат боя!");
                        winner = result[0].GetElementsByTagName("b")[0].OuterText;
                        TugrikWin = result[1].GetElementsByTagName("span")[0].OuterText;
                        TugrikWin= TugrikWin.Replace(",", "");
                        if (winner.Equals(NamePerson, StringComparison.CurrentCultureIgnoreCase))
                        {
                            TugrikWin = "-" + TugrikWin;
                            //log("победил НЕ я! Победа='" + winner + "', я='" + NamePerson + "'");
                        }
                        Rating = result[1].GetElementsByTagName("span")[1].OuterText;
                        log("Строчки: победитель=" + winner+", выбито="+TugrikWin+", Опыта="+Rating);
                        break;
                    }
            }
            return true;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string eee = "returned " + tryFindEnemies((EnemyType)cbEnemies.SelectedIndex);
            log(eee);
            return;
        }

        enum Results 
        {
            Success,
            InternalError,
            NeedToHarvest,
            AlleyNeedToWait,
            NoNeedToWait,
            NeedToWait,
            InPolice,
            RatMeeting,
            NeedMetroWork
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Results grab = tryFindEnemies((EnemyType)cbEnemies.SelectedIndex);
            if (grab == Results.InternalError) return;
            if (grab == Results.NeedMetroWork) 
            {
                log("Пытаемся раскопать руду");
                GetRudaFromMetro();
            }
            grab = GoToMetro();
            if (grab == Results.InternalError) 
            {
                log("Какие-то проблемы в метро!");
                return;
            }
            grab = GrabNanoPetriks();

        }

        int toMetro = -1;
        int toAlley = -1;
        int toPetriks = -1;

        bool needRequestSkills = true;
        void blockMainTimer() 
        {
            MainAssistantTimer.Stop();
            cbMainWork.Enabled = false;
        }

        void unblockMainTimer() 
        {
            MainAssistantTimer.Start();
            cbMainWork.Enabled = true;
        }

        private void MainAssistantTimer_Tick(object sender, EventArgs e)
        {
            if (toAlley >= 0) toAlley--;
            if (toMetro >= 0) toMetro--;
            if (toPetriks >= 0) toPetriks--;

            if (toPolice != TimeSpan.Zero)
            {
                pnlPolice.Show(); 
                UpdateTugriks();
                toPolice= toPolice.Subtract(TimeSpan.FromSeconds(1));
                lbPolice.Text = toPolice.ToString();
                return;
            }
            else pnlPolice.Hide();

            blockMainTimer();
            Results res;
            if (usedGager <= 0 || usedKirka <= 0 || needRequestSkills)
            {
                res = requestSkills();
                if (res == Results.InternalError)
                {
                    log("Внутренняя ошибка при определении кол-ва скилов! ПРЕКРАЩАЕМ РАБОТУ!");
                    unblockMainTimer();
                    StopWorking();
                }
                needRequestSkills = false;
                if (res == Results.InPolice) 
                {
                    res = requestPoliceTimer();
                    if (res == Results.InternalError) 
                    {
                        log("Внутренняя ошибка при определении сколько сидеть в милиции! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                    unblockMainTimer();
                    return;
                }
            }

            if (usedGager == 0 && cbBuyGager.Checked)
            {
                buyItem((int)ShopItems.Gager, "/shop/section/other");
                unblockMainTimer();
                needRequestSkills = true;
                return;
            }
            if (usedKirka == 0 && cbBuyKirka_tugriks.Checked) 
            {
                buyItem((int)ShopItems.Kirka_tugriki, "/shop/section/other");
                unblockMainTimer();
                needRequestSkills = true;
                return;
            }

            if (toAlley == -1 && toMetro <= 0 && (WantedPercent <= numMaximumWanted.Value || cbAntiMent.Checked))
            {
                res = tryFindEnemies((EnemyType)cbEnemies.SelectedIndex);
                if (res == Results.InternalError)
                {
                    log("Внутренняя ошибка при поиске соперника! ПРЕКРАЩАЕМ РАБОТУ!");
                    unblockMainTimer();
                    StopWorking();
                    return;
                }
                if (res == Results.InPolice)
                {
                    res = requestPoliceTimer();
                    if (res == Results.InternalError)
                    {
                        log("Внутренняя ошибка при определении сколько сидеть в милиции! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                    unblockMainTimer();
                    return;
                }
                if (res != Results.NeedMetroWork)
                {
                    res = requestTimeAlley(out toAlley);
                    if (res == Results.InternalError)
                    {
                        log("Внутренняя ошибка при определении времени на отдых от грабежей! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                }
                else log("Какие-то дела в метро остались!");
            }

            if ((toMetro == -1 && cbMetroEnabled.Checked && (toAlley >= 8*60 || toAlley <=0)) ) 
            {
                log("Идем в метро...");
                res = requestTimeMetro(out toMetro);
                if (res == Results.InPolice)
                {
                    res = requestPoliceTimer();
                    if (res == Results.InternalError)
                    {
                        log("Внутренняя ошибка при определении сколько сидеть в милиции! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                    unblockMainTimer();
                    return;
                }
                if (res == Results.InternalError) 
                {
                    log("Внутренняя ошибка при определении занятости в метро! ПРЕКРАЩАЕМ РАБОТУ!");
                    unblockMainTimer();
                    StopWorking();
                    return;
                }
                if (res == Results.NeedToHarvest) 
                {
                    GoToMetro();
                }
                if (res == Results.RatMeeting) 
                {
                    if (cbRatFight.Checked) 
                    {
                        RatFight();
                    }
                    else 
                    {
                        LeaveMetro();
                    }
                }
                if (res == Results.NoNeedToWait)
                {
                    res = GetRudaFromMetro();
                    if (res == Results.InPolice)
                    {
                        res = requestPoliceTimer();
                        if (res == Results.InternalError)
                        {
                            log("Внутренняя ошибка при определении сколько сидеть в милиции! ПРЕКРАЩАЕМ РАБОТУ!");
                            unblockMainTimer();
                            StopWorking();
                            return;
                        }
                        unblockMainTimer();
                        return;
                    }
                    if (res == Results.InternalError)
                    {
                        log("Внутренняя ошибка при раскопках! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                }
            }

            if (toPetriks <= 0 && Ruda > 5 && int.Parse(Tugriki) > 500 && cbMakePetriks.Checked) 
            {
                res = GrabNanoPetriks();
                if (res == Results.InPolice)
                {
                    res = requestPoliceTimer();
                    if (res == Results.InternalError)
                    {
                        log("Внутренняя ошибка при определении сколько сидеть в милиции! ПРЕКРАЩАЕМ РАБОТУ!");
                        unblockMainTimer();
                        StopWorking();
                        return;
                    }
                    unblockMainTimer();
                    return;
                }
                if ( res == Results.InternalError)
                {
                    log("Внутренняя ошибка при изготовлении нано-петриков! ПРЕКРАЩАЕМ РАБОТУ!");
                    unblockMainTimer();
                    StopWorking();
                    return;
                }
                if (res == Results.NeedMetroWork) 
                {
                    log("Требуется работа в метро!");
                }
            }

            TimeSpan tm ;
            tm = TimeSpan.FromSeconds(toAlley);
            if (toAlley >= 0) lbWaitAlley.Text = tm.ToString();
            tm = TimeSpan.FromSeconds(toMetro);
            if (toMetro >= 0) lbWaitMetro.Text = tm.ToString();
            tm = TimeSpan.FromSeconds(toPetriks);
            if (toPetriks >= 0) lbPetriks.Text = tm.ToString();

            unblockMainTimer();

        }

        private void StopWorking()
        {
            //cbMainWork.Checked = false;
            //return;
            log("По внутренней ошибке сбрасываем таймеры и начинаем заново!");
            toAlley = -1;
            toMetro = -1;
            toPetriks = -1;
            toPolice = TimeSpan.Zero;
            needRequestSkills = true;
            return;
        }

        private Results RatFight()
        {
            if (browser.Url.LocalPath != "/metro/") NavigateToUrl("moswar.ru/metro");
            HtmlElement elem = browser.Document.GetElementById("welcome-rat");
            if (elem == null)
            {
                log("Не нашли форму для избиения крысомахи");
                return Results.InternalError;
            }
            foreach (HtmlElement e in elem.GetElementsByTagName("button")) 
            {
                e.InvokeMember("click");
                WaitAfterNavigation();
                UpdateTugriks();
                return Results.Success;
            }
            return Results.InternalError;
        }

        private TimeSpan toPolice = TimeSpan.Zero;
        private Results requestPoliceTimer() 
        {
            NavigateToUrl("moswar.ru/player");
            if (browser.Url.LocalPath != "/police/") return Results.Success;
            HtmlElement elem = null;
            foreach (HtmlElement e in browser.Document.GetElementsByTagName("div")) 
            {
                if (e.GetAttribute("className") == "block-rounded") 
                {
                    elem = e;
                    break;
                }
            }
            if (elem == null) return Results.InternalError;
            foreach (HtmlElement e in elem.GetElementsByTagName("span")) 
            {
                if (e.GetAttribute("className") == "timer")
                {
                    int seconds = int.Parse(e.GetAttribute("timer"));
                    toPolice = TimeSpan.FromSeconds(seconds);
                    return Results.Success;
                }
            }
            return Results.InternalError;
        }
        private Results GrabNanoPetriks()
        {
            log("Идем делать петрики");
            NavigateToUrl("moswar.ru/factory/");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            if (browser.Url.LocalPath == "/metro/") return Results.NeedMetroWork;
            // 1) найдем форму изгот-я петриков
            HtmlElement elem = null;
            foreach (HtmlElement e in browser.Document.GetElementsByTagName("form"))
            {
                if (e.GetAttribute("className") == "factory-nanoptric")
                {
                    elem = e;
                    break;
                }
            }
            if (elem == null)
            {
                log("Не нашли форму для изготовления петриков");
                return Results.InternalError;
            }
            //1.5) проверяем, можем ли делать петрики или надо подождать
            HtmlElement elemWait = browser.Document.GetElementById("petriksprocess");
            if (elemWait != null)
            {
                if (elemWait.GetAttribute("className") == "value")
                {
                    toPetriks = int.Parse(elemWait.GetAttribute("timer"));
                    return Results.NeedToWait;
                }
            }
            //2) ищем кнопку "Начать переработку" и жмем на нее
            Results res = Results.InternalError;
            foreach (HtmlElement e in elem.GetElementsByTagName("button"))
            {
                if (e.GetAttribute("className") == "button")
                {
                    elem = e;
                    log("Жмем " + e.InnerText.Split('-')[0]);
                    elem.InvokeMember("click");
                    WaitAfterNavigation();
                    res = Results.Success;
                }
            }
            return res;
        }

        int usedGager = -1;
        int usedKirka = -1;
        private Results requestSkills() 
        {
            if (browser.Disposing) return Results.InternalError;
            NavigateToUrl("moswar.ru/player");
            if (browser.Url.LocalPath == "/police/") return Results.InPolice;
            if (browser.Url.LocalPath == "/metro/") return Results.NeedMetroWork;
            HtmlElement parseElem;
            Results res = Results.InternalError;
            usedGager = 0;
            usedKirka = 0;
            foreach (HtmlElement elem in browser.Document.GetElementsByTagName("img"))
            {
                if (elem.GetAttribute("src") == "http://www.moswar.ru/@/images/obj/underground3.png" && elem.Parent.TagName == "I")
                {
                    parseElem = elem.Parent.Parent; // <div class="data">
                    string uses = parseElem.GetElementsByTagName("span")[0].InnerText.Split(' ')[1];
                    usedGager = int.Parse(uses.Split('/')[1]) - int.Parse(uses.Split('/')[0])+1;
                    res = Results.Success;
                }
                if (elem.GetAttribute("src") == "http://www.moswar.ru/@/images/obj/underground2.png" && elem.Parent.TagName == "I")
                {
                    parseElem = elem.Parent.Parent; // <div class="data">
                    string uses = parseElem.GetElementsByTagName("span")[0].InnerText.Split(' ')[1];
                    usedKirka = int.Parse(uses.Split('/')[1]) - int.Parse(uses.Split('/')[0]) + 1;
                    res = Results.Success;
                }
                //else log("skip: src=" + elem.GetAttribute("src") + ", parent=" + elem.Parent.TagName);
            }
            lbUsedGager.Text = usedGager.ToString();
            lbUsedKirka.Text = usedKirka.ToString();
            return res;
        }

        enum ShopItems 
        {
            Gager = 69,
            Kirka_tugriki=70,
            Kirka_ruda=302
        }

        private Results buyItem(int num, string sectionUrl) 
        {
            string beginAddress;
            if (browser.Url != null)
                beginAddress = browser.Url.GetLeftPart(UriPartial.Scheme) + browser.Url.Host;
            else beginAddress = "moswar.ru";
            log("Идем в магазин");
            NavigateToUrl(beginAddress + sectionUrl);
            Object[] arr = new Object[2];
            arr[0] = (Object)num;
            arr[1] = (Object)sectionUrl;
            browser.Document.InvokeScript("shopBuyItem", arr);
            return Results.Success;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            MainAssistantTimer.Enabled = cbMainWork.Checked;
        }

        private void cbMaximumWanted_CheckedChanged(object sender, EventArgs e)
        {
            numMaximumWanted.Enabled = cbMaximumWanted.Checked;
        }

        private void cbAntiMent_CheckedChanged(object sender, EventArgs e)
        {
            label13.Enabled = !cbAntiMent.Checked;
            lbWanted.Enabled = !cbAntiMent.Checked;
        }
    }


    public class RequizitItem
    {
        public enum ComparisionResult
        {
            Equal,
            NonEqual,
            FormatError
        }

        public string thumb = null; // LocalPath to thumb img
        public string name = null;

        public ComparisionResult CompareToElement(HtmlElement elem) 
        {
            if (elem.GetAttribute("className") != "data") return ComparisionResult.FormatError;
            foreach (HtmlElement i in elem.GetElementsByTagName("I")) 
            {
                //if (i.GetAttribute("className") == "thumb") ;
            }
            return ComparisionResult.FormatError;
        }

    }

}
